﻿using System;
using System.Globalization;
using System.Windows.Data;
using System.Windows.Markup;

namespace Zuehlke.Blueprint.Quickstart.Architecture.Presentation.UserInterface.Localization
{
    [ContentProperty("Key")]
    public sealed class TranslateExtension : Binding, IValueConverter
    {
        #region Construction

        /// <summary>
        /// Initializes a new instance of the <see cref="TranslateExtension"/> class.
        /// </summary>
        public TranslateExtension()
            : this(string.Empty, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TranslateExtension"/> class.
        /// </summary>
        public TranslateExtension(string key)
            : this(key, null)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="TranslateExtension"/> class.
        /// </summary>
        public TranslateExtension(string key, IValueConverter keyConverter)
        {
            this.RelativeSource = RelativeSource.Self;
            this.Mode = BindingMode.OneWay;
            this.Path = TranslationManager.TranslationLanguagePath;
            
            Key = key;
            KeyConverter = keyConverter;
            this.Converter = this;
        }

        #endregion

        #region Public Functionality

        /// <summary>
        /// Gets or sets the key.
        /// </summary>
        public string Key { get; set; }

        /// <summary>
        /// Gets or sets the converter to use to convert the translated key with.
        /// </summary>
        public IValueConverter KeyConverter { get; set; }

        #endregion

        #region IValueConverter Members

        /// <inheritdoc />
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (Key == null)
            {
                throw new ArgumentException("No key provided. Specify the key to translate as constructor argument or as Key property.");
            }

            var language = value as CultureInfo;
            if (language == null)
            {
                throw new ArgumentException("No language (as value) provided.");
            }

            var translatedValue = TranslationManager.Translate(Key, language);

            if (KeyConverter != null)
            {
                return KeyConverter.Convert(translatedValue, targetType, parameter, culture);
            }

            return translatedValue;
        }

        /// <inheritdoc />
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}